// v-loading 指令
export default {
  bind(el) {
    // 创建 loading 元素
    const loadingHtml = `
      <div class="v-loading-mask" style="
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(255, 255, 255, 0.8);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 9999;
      ">
        <div class="v-loading-spinner" style="
          width: 40px;
          height: 40px;
          border: 4px solid #f3f3f3;
          border-top: 4px solid #3498db;
          border-radius: 50%;
          animation: spin 1s linear infinite;
        "></div>
      </div>
    `

    // 添加样式
    const style = document.createElement('style')
    style.textContent = `
      @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
      }
    `
    document.head.appendChild(style)

    // 保存 loading 元素引用
    el.loadingElement = loadingHtml
    el.style.position = 'relative'
  },

  update(el, binding) {
    if (binding.value !== binding.oldValue) {
      if (binding.value) {
        // 显示 loading
        if (!el.querySelector('.v-loading-mask')) {
          el.insertAdjacentHTML('beforeend', el.loadingElement)
        }
      } else {
        // 隐藏 loading
        const loadingMask = el.querySelector('.v-loading-mask')
        if (loadingMask) {
          loadingMask.remove()
        }
      }
    }
  },

  unbind(el) {
    // 清理 loading 元素
    const loadingMask = el.querySelector('.v-loading-mask')
    if (loadingMask) {
      loadingMask.remove()
    }
  },
}
